package org.example.interceptor;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.example.config.JwtConfig;
import org.example.exception.ServiceException;
import org.example.model.User;
import org.example.repository.UserRepository;
import org.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 微信小程序认证拦截器
 * 专门用于处理小程序请求的身份验证和授权
 */
@Component
public class MiniAppAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtConfig jwtConfig;
    
    @Autowired
    private UserRepository userRepository;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // OPTIONS请求（预检请求）直接放行
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        
        // 获取请求头中的token
        String token = request.getHeader("Authorization");
        
        // 检查token是否为空
        if (!StringUtils.hasText(token) || !token.startsWith("Bearer ")) {
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":0,\"msg\":\"未授权，请先登录\",\"data\":null}");
            return false;
        }
        
        // 提取实际的token值（去掉"Bearer "前缀）
        token = token.substring(7);
        
        try {
            // 验证并解析token
            Claims claims = Jwts.parser()
                    .setSigningKey(jwtConfig.getJwtSecret())
                    .parseClaimsJws(token)
                    .getBody();
            
            // 从token中获取openid
            String openid = claims.getSubject();
            
            // 查询用户是否存在
            User user = userRepository.findByOpenid(openid);
            if (user == null) {
                response.setStatus(401);
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().write("{\"code\":0,\"msg\":\"用户不存在\",\"data\":null}");
                return false;
            }
            
            // 将用户信息存入ThreadLocal，以便在后续的处理中使用
            ThreadLocalUtil.addCurrentUser(user);
            
            // 允许请求继续处理
            return true;
        } catch (Exception e) {
            // token验证失败
            response.setStatus(401);
            response.setContentType("application/json;charset=UTF-8");
            response.getWriter().write("{\"code\":0,\"msg\":\"无效的令牌或令牌已过期，请重新登录\",\"data\":null}");
            return false;
        }
    }
    
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 请求结束后，清除ThreadLocal中的数据，防止内存泄漏
        ThreadLocalUtil.remove();
    }
} 